package com.software.loginregister.activity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.software.loginregister.R;
import com.software.loginregister.adapter.ManualFoodAdapter;
import com.software.loginregister.entity.FoodItem;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.FoodRecognitionDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ManualInputFoodActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ManualFoodAdapter adapter;
    private Button btnAddToFridge;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manual_input_food);

        initViews();
        setupRecyclerView();
        setupSwipeRefresh();
        setStatusBar();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        btnAddToFridge = findViewById(R.id.result_btn_AddToFridge);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);

        btnAddToFridge.setOnClickListener(v -> addFoodsToFridge());

        // 新增：添加食材按钮
        Button btnAddFood = findViewById(R.id.btnAddFood);
        btnAddFood.setOnClickListener(v -> showAddFoodDialog());
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ManualFoodAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    private void setupSwipeRefresh() {
        swipeRefreshLayout.setColorSchemeResources(R.color.hot_title_background);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 刷新操作，这里可以重新加载数据
            swipeRefreshLayout.setRefreshing(false);
        });
    }

    private void setStatusBar() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);
    }

    // 新增：显示添加食材对话框
    private void showAddFoodDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_food, null);

        EditText etName = dialogView.findViewById(R.id.etName);
        EditText etQuantity = dialogView.findViewById(R.id.etQuantity);
        EditText etUnit = dialogView.findViewById(R.id.etUnit);
        EditText etStorage = dialogView.findViewById(R.id.etStorage);
        EditText etDays = dialogView.findViewById(R.id.etDays);

        builder.setView(dialogView)
                .setTitle("添加食材")
                .setPositiveButton("确定", (dialog, which) -> {
                    String name = etName.getText().toString();
                    int quantity = Integer.parseInt(etQuantity.getText().toString());
                    String unit = etUnit.getText().toString();
                    String storage = etStorage.getText().toString();
                    int days = Integer.parseInt(etDays.getText().toString());

                    FoodItem newItem = new FoodItem(name, quantity, unit, storage, days);
                    adapter.addItem(newItem);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void addFoodsToFridge() {
        Long userId = SharedPreferencesUtil.getUserId(this);
        if (userId == null) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        List<FoodRecognitionDTO> foods = adapter.getFoodRecognitionList();
        if (foods == null || foods.isEmpty()) {
            Toast.makeText(this, "没有可添加的食材", Toast.LENGTH_SHORT).show();
            return;
        }

        RetrofitClient.getInstance()
                .getRefrigeratorApi()
                .addFoodsToFridge(userId, foods)
                .enqueue(new Callback<Result<String>>() {
                    @Override
                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<String> result = response.body();
                            if (result.getCode() == 1) {
                                Toast.makeText(ManualInputFoodActivity.this, "已成功添加到冰箱", Toast.LENGTH_SHORT).show();
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                Toast.makeText(ManualInputFoodActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(ManualInputFoodActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable t) {
                        Toast.makeText(ManualInputFoodActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

